#!/bin/bash
set -e

cd /app

export LC_ALL=en_US.UTF-8

# Ensure the huginn user has access to the required directories
sudo -u huginn -H mkdir -p tmp/pids tmp/cache tmp/sockets log
sudo -u huginn -H touch log/production.log
# Get rid of annoying "fatal: Not a git repository (or any of the parent directories): .git" messages
sudo -u huginn -H git init

# HACK: We need a database connection to precompile the assets, use sqlite for that
cp Gemfile Gemfile.bak
echo "gem 'sqlite3', '~> 1.3.11'" >> /app/Gemfile
RAILS_ENV=production APP_SECRET_TOKEN=secret DATABASE_ADAPTER=sqlite3 ON_HEROKU=true bundle install --without test development --path vendor/bundle -j 4
RAILS_ENV=production APP_SECRET_TOKEN=secret DATABASE_ADAPTER=sqlite3 ON_HEROKU=true bundle exec rake assets:clean assets:precompile

# Bundle again to get rid of the sqlite3 gem
cp Gemfile.bak Gemfile
RAILS_ENV=production APP_SECRET_TOKEN=secret DATABASE_ADAPTER=sqlite3 ON_HEROKU=true bundle install --without test development --path vendor/bundle -j 4
chown huginn:huginn Gemfile.lock

# Configure the unicorn server
mv config/unicorn.rb.example config/unicorn.rb
sed -ri 's/^listen .*$/listen ENV["PORT"]/' config/unicorn.rb
sed -ri 's/^stderr_path.*$//' config/unicorn.rb
sed -ri 's/^stdout_path.*$//' config/unicorn.rb
